package com.example.tabbar.fragment


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.example.tabbar.R
import com.example.tabbar.databinding.FragmentSearchBinding



class SearchFragment : Fragment() {
    private var binding: FragmentSearchBinding? = null
    private var sampling:TextView? = null
    private var audit: TextView? = null
    private var samplingFragment: SamplingDataFragment? = null
    private var auditFragment: AuditFragment? = null
    private var currentChildFragment: Fragment? = null
    // 添加变量记录上一次的采样数据界面类型
    private var lastSamplingFragmentType: Int = 0 // 0 表示平铺界面，1 表示详细界面


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentSearchBinding.inflate(inflater, container, false)
        return binding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupInitialFragment(savedInstanceState)

        initView()

    }

    private fun initView() {
        sampling = binding!!.samplingTitle
        audit = binding!!.auditTitle

        sampling?.isSelected = true

        sampling?.setOnClickListener {
            sampling?.isSelected = true
            audit?.isSelected = false
            switch(lastSamplingFragmentType)
        }
        audit?.setOnClickListener {
            sampling?.isSelected = false
            audit?.isSelected = true
            switch(1)
        }

    }

    private fun setupInitialFragment(savedInstanceState: Bundle?) {
        if (savedInstanceState == null) {
            samplingFragment = SamplingDataFragment.newInstance()
            childFragmentManager
                .beginTransaction()
                .add(R.id.search_content,samplingFragment!!,SamplingDataFragment::class.java.simpleName)
                .commit()
            currentChildFragment = samplingFragment
        }else {
            samplingFragment = childFragmentManager.findFragmentByTag(SamplingDataFragment::class.java.simpleName) as SamplingDataFragment?
            auditFragment = childFragmentManager.findFragmentByTag(AuditFragment::class.java.simpleName) as AuditFragment?

            // 恢复当前显示的fragment
            samplingFragment?.let {
                if (!it.isHidden) {
                    currentChildFragment = it
                }
            }

            auditFragment?.let {
                if (!it.isHidden) {
                    currentChildFragment = it
                }
            }
        }
    }
    private fun switch(tabIndex: Int) {

        var toShowFragment: Fragment? = null
        when (tabIndex) {
            0 -> {
                // 检查是否有数据详情页面在返回栈中
                if (childFragmentManager.backStackEntryCount > 0) {
                    // 查找详情页面
                    val roomDataFragment = childFragmentManager.findFragmentByTag(RoomDataDetailsFragment::class.java.simpleName)
                    val detailsDataFragment = childFragmentManager.findFragmentByTag(DetailsDataFragment::class.java.simpleName)

                    if (roomDataFragment != null && roomDataFragment.isAdded) {
                        toShowFragment = roomDataFragment
                    } else if (detailsDataFragment != null && detailsDataFragment.isAdded) {
                        toShowFragment = detailsDataFragment
                    } else{
                        // 如果详情页面不存在但返回栈有记录，清理返回栈并显示采样列表
                        childFragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
                        if (samplingFragment == null) {
                            samplingFragment = SamplingDataFragment.newInstance()
                        }
                        toShowFragment = samplingFragment
                    }
                } else {
                    // 直接显示采样列表
                    if (samplingFragment == null) {
                        samplingFragment = SamplingDataFragment.newInstance()
                    }
                    toShowFragment = samplingFragment
                }
                lastSamplingFragmentType = 0
            }
            1 -> {
                // 切换到审计追踪，隐藏可能存在的详情页面
                hideAllDetailFragments()

                if (auditFragment == null) {
                    auditFragment = AuditFragment.newInstance()
                }
                toShowFragment = auditFragment
            }
        }


        // 使用事务正确管理 Fragment 显示
        val transaction = childFragmentManager.beginTransaction()

        // 如果当前 Fragment 存在且不是目标 Fragment，则隐藏它
        currentChildFragment?.let {
            if (it != toShowFragment && !it.isHidden) {
                transaction.hide(it)
            }
        }

        // 处理目标 Fragment
        toShowFragment?.let {
            if (!it.isAdded) {
                // 如果 Fragment 还未添加，则添加它
                transaction.add(R.id.search_content, it, it.javaClass.simpleName)
            } else if(it.isHidden) {
                // 如果 Fragment 已添加，确保它被显示
                transaction.show(it)
            } else {

            }
        }

        transaction.commit()
        currentChildFragment = toShowFragment
    }
    fun navigateToDetail(userId: Int?, locationId: Int?,dataType: String? = null,roomName: String? = null) {
        val dataFragment = when (dataType) {
            "ROOM_DATA" -> RoomDataDetailsFragment.newInstance(userId, locationId,roomName)
            "DETAILS_DATA" -> DetailsDataFragment.newInstance()
            // 后续添加新的数据详情页面只需在这里增加分支
            else -> RoomDataDetailsFragment.newInstance(userId, locationId,roomName)
        }

        // 根据不同类型使用不同的 tag
        val tag = when (dataType) {
            "DETAILS_DATA" -> DetailsDataFragment::class.java.simpleName
            else -> RoomDataDetailsFragment::class.java.simpleName
        }

        childFragmentManager.beginTransaction()
            .hide(samplingFragment!!)
            .add(R.id.search_content, dataFragment, tag)
            .addToBackStack(null)
            .commit()

        currentChildFragment = dataFragment
    }

    fun backToSamplingList() {
        // 弹出详情页面，回到采样列表
        childFragmentManager.popBackStack()
        currentChildFragment = samplingFragment
    }
    // 隐藏所有详情数据页面
    private fun hideAllDetailFragments() {
        val transaction = childFragmentManager.beginTransaction()

        // 隐藏 RoomDataDetailsFragment
        val roomDetailFragment = childFragmentManager.findFragmentByTag(RoomDataDetailsFragment::class.java.simpleName)
        if (roomDetailFragment != null && roomDetailFragment.isAdded && !roomDetailFragment.isHidden) {
            transaction.hide(roomDetailFragment)
        }

        // 隐藏 DetailsDataFragment
        val otherDetailFragment = childFragmentManager.findFragmentByTag(DetailsDataFragment::class.java.simpleName)
        if (otherDetailFragment != null && otherDetailFragment.isAdded && !otherDetailFragment.isHidden) {

            transaction.hide(otherDetailFragment)
        }

        transaction.commit()
    }


    companion object {

        @JvmStatic
        fun newInstance() =
            SearchFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }
}